package com.justme.shipdfer.controller;

import com.justme.shipdfer.bean.param.PdfBody;
import com.justme.shipdfer.service.PdferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.validation.constraints.NotBlank;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author shiv
 * @create 2021/4/11 4:49 下午
 */
@Validated
@RestController
@RequestMapping("/v1/pdf")
public class PdferController {

    @Autowired
    private PdferService pdferService;

    /**
     * pdf 预览
     * 仅仅是预览模板 不会渲染数据，不是最终效果
     *
     * @param templateKey 模板key
     * @return 预览结果
     */
    @GetMapping("/preview")
    public ResponseEntity<StreamingResponseBody> previewPdf(@NotBlank(message = "参数不能为空") String templateKey) {
        PdfBody pdfBody = new PdfBody();
        pdfBody.setTemplateKey(templateKey);

        StreamingResponseBody responseBody = outputStream -> pdferService.generatePdf(pdfBody, outputStream, true);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "inline");

        return ResponseEntity.status(HttpStatus.OK)
                .headers(httpHeaders)
                .body(responseBody);
    }

    /**
     * 生成pdf
     *
     * @param pdfBody 请求数据
     * @return 结果
     * @throws UnsupportedEncodingException 编码异常
     */
    @PostMapping("/generate")
    public ResponseEntity<StreamingResponseBody> generatePdf(@RequestBody PdfBody pdfBody) throws UnsupportedEncodingException {
        StreamingResponseBody responseBody = outputStream -> pdferService.generatePdf(pdfBody, outputStream, false);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION,
                String.format("attachment; filename=%s.pdf", URLEncoder.encode(pdfBody.getTemplateKey(), "utf-8")));

        return ResponseEntity.status(HttpStatus.OK)
                .headers(httpHeaders)
                .body(responseBody);
    }

}
